package com.mubolg.template;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mubolg.properties.AppSettingProperties;

public class AppWeChatTemplate {

    private AppSettingProperties appSettingProperties;
    public AppWeChatTemplate(AppSettingProperties appSettingProperties) {
        this.appSettingProperties = appSettingProperties;
    }

    public String getOpenID(String code){
        //拼接Url
        String url = String.format(appSettingProperties.getOpenIdUrl(),appSettingProperties.getAppId(),appSettingProperties.getSecret(), code);
        //获取Openid
        String JsonResultStr =  HttpUtil.get(url);
        //转换为对象
        JSONObject openIdTempObj = JSONUtil.parseObj(JsonResultStr);
        //获取openid
        String openId = openIdTempObj.getStr("openid");
        if (StrUtil.isEmpty(openId)){
            throw new RuntimeException("获取openid失败！");
        }
        return openId;
    }
    public String getAccessToken() {
        //拼接Url
        String AccessUrl = String.format(appSettingProperties.getAccessTokenUrl(),appSettingProperties.getAppId(),appSettingProperties.getSecret());
        //获取请求结果Access
        String JsonResultAccess =  HttpUtil.get(AccessUrl);
        JSONObject AccessObject = JSONUtil.toBean(JsonResultAccess, JSONObject.class);
        String accessToken = AccessObject.getStr("access_token");
        if (StrUtil.isEmpty(accessToken)){
            throw new RuntimeException("获取accessToken失败！");
        }
        return accessToken;
    }
    public String getPhone(String code) {
        String accessToken = this.getAccessToken();
        String PhoneUrl = String.format(appSettingProperties.getPhoneUrl(),accessToken);
        JSONObject body = new JSONObject();
        body.set("code",code);
        //获取请求结果Phone
        String JsonResultPhone =  HttpUtil.post(PhoneUrl,body.toString());
        //转为JSON对象
        JSONObject jsonObject = new JSONObject(JsonResultPhone);
        Integer errcode = jsonObject.getInt("errcode");
        if (errcode != 0){
            throw new RuntimeException("获取手机号失败！");
        }
        //取手机号
        String phoneNunber = jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");
        if (StrUtil.isEmpty(phoneNunber)){
            throw new RuntimeException("获取手机号失败！");
        }
        return phoneNunber;

    }

}
